import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import ViewerRetrieveStudyData from '../components/ViewerRetrieveStudyData';
import { utils } from '@ohif/core';
import { Result } from 'antd';
import PageLoadingSpin from '../components/PageLoadingSpin';

const RimagViewerRouting = ({ match, location }) => {
  const [loading, setLoading] = useState({loading: true, error: null });
  const [data, setData] = useState({});

  const { accessKey } = match.params;
  const { pathname } = location;

  let parts = [];
  if (pathname) parts = pathname.split('/');
  let prefix = '';
  if (parts.length > 1 && parts[1] !== 'vw') {
    prefix = '/' + parts[1];
  }

  const fetchData = async () => {
    const { data, status, message } = await utils.xhrRequest({
      method: 'GET',
      url: `${prefix}/api/vw/get/${accessKey}`,
    }).catch(err => {
      setLoading({ error: `Get image data failed: ${err}`});
    });

    if (status !== 200 || !data) {
      setLoading({ error: message ? message : 'Unknown error!', loading: false });
      return;
    }

    let arcUrl = '/api/dcm' + data.relationList[0].arcUrl;
    const server = {
      name: 'DCMARCHIVE',
      wadoUriRoot: arcUrl + '/wado',
      qidoRoot: arcUrl + '/rs',
      wadoRoot: arcUrl + '/rs',
      metadataRoot: '/file' + data.relationList[0].metadata,
      qidoSupportsIncludeField: true,
      imageRendering: 'wadouri',
      thumbnailRendering: 'wadouri',
      enableStudyLazyLoad: true,
      supportsFuzzyMatching: true,
    };
    const studyUIDs = data.relationList.reduce((uids, item) => {
      uids.push(item.studyUid);
      return uids;
    }, []);
    // not used
    const seriesUIDs = [];

    setData({ server, studyUIDs, seriesUIDs });
    setLoading({ error: null, loading: false });
  };

  useEffect(() => { fetchData(); }, []);

  return (
    loading.loading ? (
      <PageLoadingSpin />
    ) : (
      loading.error ? (
        <Result status="error" title={loading.error} />
      ) : (
        <ViewerRetrieveStudyData
          server={data.server}
          studyInstanceUIDs={data.studyUIDs}
          seriesInstanceUIDs={data.seriesUIDs}
        />
      )
    )
  );
}

RimagViewerRouting.propTypes = {
  match: PropTypes.shape({
    params: PropTypes.shape({
      accessKey: PropTypes.string.isRequired,
    }),
  }),
  location: PropTypes.any,
};

export default RimagViewerRouting;
